import 'package:flutter_admin/api/odoo/sale_orderoutstock_odoo_api.dart';
import 'package:flutter_admin/models/odoo/sale_orderoutstock.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/loading_dialog.dart';
import 'package:flutter_admin/pages/odoo/sale_orderoutstock/sale_orderoutstock_dialog.dart';
import 'package:flutter_admin/pages/odoo/sale_orderoutstock/sale_orderoutstock_excel.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';
class SaleOrderoutstockList extends StatefulWidget {
  SaleOrderoutstockList({Key? key}) : super(key: key);

  @override
  _SaleOrderoutstockListState createState() => _SaleOrderoutstockListState();
}

class _SaleOrderoutstockListState extends State<SaleOrderoutstockList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  SaleOrderoutstock saleOrderoutstock = SaleOrderoutstock();
  DateFormat format = DateFormat('yyyy-MM-dd');

  List<SaleOrderoutstock> selectedList = [];

  @override
  void initState() {
    super.initState();
    saleOrderoutstock.startDate = Utils.getDate();
    saleOrderoutstock.endDate = Utils.getDate();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 180,
            label: '发货开始日期',
            value: saleOrderoutstock.startDate,
            lastDate: isNotBlank(saleOrderoutstock.endDate)
                ? format.parse(saleOrderoutstock.endDate!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              saleOrderoutstock.startDate = v;
              setState(() {});
            },
            onSaved: (v) {
              saleOrderoutstock.startDate = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '发货结束日期',
            value: saleOrderoutstock.endDate,
            firstDate: isNotBlank(saleOrderoutstock.startDate)
                ? format.parse(saleOrderoutstock.startDate!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              saleOrderoutstock.endDate = v;
              setState(() {});
            },
            onSaved: (v) {
              saleOrderoutstock.endDate = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      availableRowsPerPage: [10],
      // onRowsPerPageChanged: (int size) {
      //   page.size = size;
      //   page.current = 1;
      //   _loadData();
      // },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('销售订单号')),
        DataColumn(label: Text('下单日期')),
        DataColumn(label: Text('发货日期')),
        DataColumn(label: Text('交货周期（天）')),
        DataColumn(label: Text('产品编码')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('数量')),
        DataColumn(label: Text('客户名称')),
        DataColumn(label: Text('产品核算名称')),
        DataColumn(label: Text('产品种类')),
      ],
      getCells: (m) {
        SaleOrderoutstock saleOrderoutstock = SaleOrderoutstock.fromMap(m);
        return [
          DataCell(Text(saleOrderoutstock.contractid ?? '--')),
          DataCell(Text(saleOrderoutstock.orderDate ?? '--')),
          DataCell(Text(saleOrderoutstock.outstocktime ?? '--')),
          DataCell(Text(saleOrderoutstock.dayCount ?? '--')),
          DataCell(Text(saleOrderoutstock.productid ?? '--')),
          DataCell(Text(saleOrderoutstock.productname ?? '--')),
          DataCell(Text(saleOrderoutstock.productspec ?? '--')),
          DataCell(Text(saleOrderoutstock.quantity ?? '--')),
          DataCell(Text(saleOrderoutstock.customername ?? '--')),
          DataCell(Text(saleOrderoutstock.accountingName ?? '--')),
          DataCell(Text(saleOrderoutstock.cate ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
          label: "导出",
          onPressed: () => _generateExcel(),
          iconData: Icons.import_export_outlined,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  Future<dynamic> findAll() async {
    formKey.currentState?.save();
    var result;
    ResponseBodyApi responseBodyApi =
        await SaleOrderoutstockOdooApi.findAll(data: {
      "domainList": saleOrderoutstock.toDomainList(),
    });
    if (responseBodyApi.success!) {
      result = responseBodyApi.data;
      //     .map<SaleOrderoutstock>((e) => SaleOrderoutstock.fromMap(e))
      //     .toList() ??
      // [];
    }
    return result;
  }

  _generateExcel() async {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return LoadingDialog(
            title: "导出中...",
            isCancel: false,
          );
        });
    var result = await findAll();
    if (result == null) {
      return;
    }
    List<SaleOrderoutstock> dataList = [];
    dataList = result['data']
            .map<SaleOrderoutstock>((e) => SaleOrderoutstock.fromMap(e))
            .toList() ??
        [];

    SaleOrderoutstockExcel.generateExcel(
        fileName: "订单交货期统计分析",
        datatable: dataList,
        averageValue: result['average_value'].toString());
    // 关闭遮罩
    Navigator.pop(context, true);
  }

  _reset() {
    saleOrderoutstock = SaleOrderoutstock();
    formKey.currentState!.reset();
    saleOrderoutstock.startDate = Utils.getDate();
    saleOrderoutstock.endDate = Utils.getDate();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    // tableKey.currentState!.loadData(PageModel());
    ResponseBodyApi responseBodyApi = await SaleOrderoutstockOdooApi.page(
        data: {"page": page, "domainList": saleOrderoutstock.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SaleOrderoutstockDialog(),
      ),
    ).then((v) {
      if (v != null) {
        saleOrderoutstock = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<SaleOrderoutstock>((e) => SaleOrderoutstock.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.dmsFile) {
          _generateExcel();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          child: ListTile(
            leading: const Icon(Icons.import_export_outlined),
            title: Text('导出'),
          ),
        ),
      ],
    );
  }
}
